<template>
  <!-- <el-container class="main" v-loading="loading" element-loading-text="加载中..."> -->
  <div
    ref="dom"
    v-loading="loading"
    element-loading-text="加载中..."
    style="display: flex; flex-direction: column; flex: 1; height: 100%"
  >
    <div class="header">
      <div class="btn_group">
        <HPlainButton @click="addFault">添加故障说明</HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeAll(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(2)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(3)">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="filter">
        <el-input
          class="input-with"
          v-model="name"
          placeholder="搜索故障名称"
          clearable
          @keyup.enter="getFaultList"
        />
        <el-input
          class="input-with"
          v-model="content"
          placeholder="搜索故障内容"
          clearable
          @keyup.enter="getFaultList"
        />
        <el-input
          class="input-with"
          v-model="solution"
          placeholder="搜索解决方案"
          clearable
          @keyup.enter="getFaultList"
        />
        <HButton type="primary" @click="getFaultList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
        <HButton @click="clearVlaue">
          <el-icon>
            <RefreshRight />
          </el-icon>
          重置
        </HButton>
      </div>
    </div>

    <!-- 表格内容 -->
    <div class="table">
      <el-table
        ref="faulTableDom"
        border
        stripe
        resizable
        :data="faultData"
        style="position: absolute"
        height="100%"
        @selection-change="handleChange"
        @row-dblclick="doubleClick"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="55" />
        <el-table-column show-overflow-tooltip prop="name" label="故障名称" max-width="230" />
        <el-table-column
          show-overflow-tooltip
          prop="knowledgeType"
          label="知识库类型"
          max-width="230"
        />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <HStatus v-if="scope.row.status === false">启用</HStatus>
            <HStatus v-if="scope.row.status === true" type="info">禁用</HStatus>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="content" label="故障内容" max-width="230" />
        <el-table-column show-overflow-tooltip prop="solution" label="解决方案" max-width="230" />
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="150" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="150" />
        <el-table-column fixed="right" label="操作" width="50">
          <template #default="scope">
            <span class="xy_main_btn" @click="doubleClick(scope.row)">编辑</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <div class="footer">
        <Pagination
          ref="pagination"
          :list_total="listTotal"
          @size-change="getFaultList"
          @current-change="getFaultList"
        />
      </div>
    </div>
  </div>
  <!-- </el-container> -->

  <!-- 新增故障说明 -->
  <HModal v-model="addFault_dialogVisible">
    <template #header>
      <div class="my-header">
        <h3 class="title">{{ faultTitle }}</h3>
      </div>
    </template>
    <div v-loading="faultLoading" element-loading-text="加载中...">
      <el-form
        ref="faultFormRef"
        :rules="faultRules"
        :model="faultForm"
        label-width="110px"
        class="form_content"
        @validate="handleFormValidate"
      >
        <!--故障名称-->
        <el-form-item
          label="故障名称"
          :class="{ form_item: formValidateResult, validate_fail: !formValidateResult }"
          prop="name"
        >
          <el-input v-model="faultForm.name" placeholder="请输入故障名称" clearable></el-input>
        </el-form-item>

        <!--所属知识库类型-->
        <el-form-item label="所属知识库类型" class="form_item">
          <KnowledgeMultiple
            ref="knowledgeMultipleRef"
            :oldKnowledgeTypeVo="faultForm.knowledgeTypeVos"
          />
        </el-form-item>

        <!--故障内容-->
        <el-form-item label="故障内容" class="form_item">
          <el-input
            v-model="faultForm.content"
            show-word-limit
            type="textarea"
            placeholder="请输入故障内容"
            rows="2"
            clearable
          />
        </el-form-item>

        <!--故障图片-->
        <el-form-item label="故障图片" class="form_item">
          <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap">
            <template v-for="(img, imgIndex) in faultImg" :key="imgIndex">
              <el-dropdown>
                <el-image
                  :src="img.imgUrl"
                  :initial-index="imgIndex"
                  :preview-src-list="faultImg.map((item) => item.imgUrl)"
                  style="width: 40px; height: 40px"
                />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleRemove_fault(img)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
            <el-upload
              action="#"
              multiple
              list-type="picture-card"
              accept="image/*"
              :on-change="handleUpload_fault"
              :auto-upload="false"
              v-if="faultImg.length < 10"
              :show-file-list="false"
            >
              <el-icon size="24px">
                <Plus />
              </el-icon>
            </el-upload>
          </div>
        </el-form-item>

        <!--解决方案-->
        <el-form-item label="解决方案" class="form_item">
          <el-input
            v-model="faultForm.solution"
            show-word-limit
            type="textarea"
            placeholder="请输入解决方案"
            rows="2"
            clearable
          />
        </el-form-item>

        <!--解决图片-->
        <el-form-item label="解决图片" class="form_item">
          <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap">
            <template v-for="(img, imgIndex) in solveImg" :key="imgIndex">
              <el-dropdown>
                <el-image
                  :src="img.imgUrl"
                  :initial-index="imgIndex"
                  :preview-src-list="solveImg.map((item) => item.imgUrl)"
                  style="width: 40px; height: 40px"
                />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleRemove_solve(img)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
            <el-upload
              action="#"
              accept="image/*"
              multiple
              v-if="solveImg.length < 10"
              list-type="picture-card"
              :on-change="handleUpload_solve"
              :auto-upload="false"
              :show-file-list="false"
            >
              <el-icon size="24px">
                <Plus />
              </el-icon>
            </el-upload>
          </div>
        </el-form-item>

        <!--故障状态-->
        <el-form-item label="故障状态" class="form-item">
          <div style="display: flex; align-items: center; gap: 5px">
            <el-switch v-model="faultForm.status" :active-value="false" :inactive-value="true" />
            <span v-if="!faultForm.status">启用</span>
            <span v-else>禁用</span>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <template #footerLeft>
      <HPlainBgButton type="error" is-modal v-if="faultTitle === '编辑故障'" @click="changeAll(4)"
        >删除</HPlainBgButton
      >
    </template>

    <template #footerRight>
      <HButton is-modal type="primary" @click="saveAddFault(faultFormRef)">确定</HButton>
      <HButton is-modal @click="onClose">取消</HButton>
    </template>
  </HModal>

  <el-dialog v-model="img_dialogVisible" top="8vh">
    <img w-full :src="dialogImageUrl" alt="Preview Image" class="img_view" />
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, onMounted, onBeforeUnmount, reactive, markRaw } from 'vue'
  import {
    Search,
    Delete,
    Warning,
    RefreshRight,
    ArrowDown,
    CircleCheck,
    Plus,
  } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox, FormItemProp } from 'element-plus'
  import type { UploadFile, FormInstance } from 'element-plus'
  import Pagination from '../../../../components/Pagination/index.vue'
  import { knowledgeAnnexUpload, deleteFile } from '@/api/upload'
  import KnowledgeMultiple from '@/components/Knowledge/knowledgeMultiple.vue'
  import { faultList, saveFault, disableFault, deleteFault, detailFault } from '@/api/knowledge'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HPlainBgButton from '@/components/common/button/HPlainBgButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import { HModal } from '@/components/common'

  /**
   * 表单验证结果
   */
  const formValidateResult = ref(true)

  /**
   * 表达那验证事件
   */
  const handleFormValidate = (prop: FormItemProp, isValid: boolean) => {
    formValidateResult.value = isValid
  }

  /**
   * 弹窗关闭事件
   */
  const onClose = () => {
    addFault_dialogVisible.value = false
    formValidateResult.value = true
  }

  const loading = ref(false)
  const lookW = ref(null)
  const dom = ref()
  const addFault_dialogVisible = ref(false)
  const name = ref('') // 搜索框
  const content = ref('') // 故障内容
  const solution = ref('') // 解决方案内容

  const faulTableDom = ref() // 故障列表Dom
  const faultData = ref([]) // 故障列表数据
  const pagination = ref() // 故障分页Dom
  const listTotal = ref(0) // 故障总数量

  const faultTitle = ref('')
  const faultFormRef = ref()
  const faultLoading = ref(false)
  const knowledgeMultipleRef = ref() // 知识库类型Ref对象

  // 表单数据
  const faultForm = reactive({
    id: null,
    name: '',
    status: false,
    content: '',
    solution: '',
    annexs: [],
    delAnnexIds: [],
    solutions: [],
    delSolutionIds: [],
    knowledgeTypeVos: [
      // 知识库分类对象
      {
        id: '', // 关联对象表ID，新增不必传
        knowledgeTypeId: '', // 	知识库分类ID
      },
    ],
    delRelationIds: [], // 删除知识库的关联对象ID
  })

  const dialogImageUrl = ref('')
  const img_dialogVisible = ref(false)
  const disabled = ref(false)

  // 获取数据
  const getAllData = async () => {
    await getFaultList()
  }

  const resizeObserver = new ResizeObserver((val) => {
    lookW.value = val[0].borderBoxSize[0].blockSize + 10
  })

  // 验证规则
  const faultRules = reactive({
    name: [{ required: true, message: '请输入类型名称', trigger: ['blur', 'change'] }],
    faultTypeId: [{ required: true, message: '请选择故障类型', trigger: 'blur' }],
  })

  // 故障图片
  const faultImg = ref<Array<{ file?: UploadFile; imgUrl: string; uid: number }>>([])

  /**
   * 故障图片上传事件
   * @param {object} file - 文件
   */
  const handleUpload_fault = (file: UploadFile) => {
    const fileReader = new FileReader()
    fileReader.readAsDataURL(file.raw)
    fileReader.onload = () => {
      if (!file.raw.type.includes('image')) {
        ElMessage({
          type: 'error',
          message: '只能上传图片',
          grouping: false,
        })
        return false
      }
      if (file.raw.size / 1024 / 1024 > 50) {
        ElMessage({
          type: 'error',
          message: '图片大小不能超过50M!',
          grouping: true,
        })
        return false
      }
      if (faultImg.value.length >= 10) {
        ElMessage({
          type: 'error',
          message: '最多只能上传10张图片!',
          grouping: true,
        })
        return false
      }
      faultImg.value.push({ file, imgUrl: fileReader.result as string, uid: file.uid })
    }
  }

  // 删除故障图片
  const handleRemove_fault = (file: { file?: UploadFile; imgUrl: string; uid: number }) => {
    faultImg.value = faultImg.value.filter((o) => file.uid !== o.uid)
    if (faultForm.delAnnexIds.includes(file.uid) == false) {
      faultForm.delAnnexIds.push(file.uid)
    }
  }

  // 解决图片
  const solveImg = ref<Array<{ file?: UploadFile; imgUrl: string; uid: number }>>([])

  // 上传解决图片
  const handleUpload_solve = (file: UploadFile) => {
    const fileReader = new FileReader()
    fileReader.readAsDataURL(file.raw)
    fileReader.onload = () => {
      if (!file.raw.type.includes('image')) {
        ElMessage({
          type: 'error',
          message: '只能上传图片',
          grouping: false,
        })
        return false
      }
      if (file.raw.size / 1024 / 1024 > 50) {
        ElMessage({
          type: 'error',
          message: '图片大小不能超过50M!',
          grouping: true,
        })
        return false
      }
      if (solveImg.value.length >= 10) {
        ElMessage({
          type: 'error',
          message: '最多只能上传10张图片!',
          grouping: true,
        })
        return false
      }
      solveImg.value.push({ file, imgUrl: fileReader.result as string, uid: file.uid })
    }
  }

  // 删除解决图片
  const handleRemove_solve = (file: { file?: UploadFile; imgUrl: string; uid: number }) => {
    solveImg.value = solveImg.value.filter((o) => o.uid !== file.uid)
    if (faultForm.delSolutionIds.includes(file.uid) == false) {
      faultForm.delSolutionIds.push(file.uid)
    }
  }

  // 获取故障列表
  const getFaultList = async () => {
    loading.value = true
    const data = {
      content: content.value,
      limit: pagination.value.size,
      name: name.value,
      page: pagination.value.current,
      solution: solution.value,
    }
    await faultList(data).then((res) => {
      faultData.value = res.data.data.rows
      listTotal.value = Number(res.data.data.total)
      loading.value = false
    })
  }

  // 添加故障说明
  const addFault = async () => {
    faultTitle.value = '添加故障'
    addFault_dialogVisible.value = true
    faultLoading.value = true
    faultForm.annexs = []
    faultForm.content = ''
    faultForm.id = null
    faultForm.name = ''
    faultForm.solution = ''
    faultForm.solutions = []
    faultForm.status = false
    faultImg.value = []
    solveImg.value = []
    faultForm.delAnnexIds = []
    faultForm.delSolutionIds = []
    faultLoading.value = false
  }

  // 编辑故障说明
  const doubleClick = async (val) => {
    faultTitle.value = '编辑故障'
    addFault_dialogVisible.value = true
    faultLoading.value = true
    faultImg.value = []
    solveImg.value = []
    faultForm.delAnnexIds = []
    faultForm.delSolutionIds = []
    const res = await detailFault(val.id)
    const data = res.data.data.row
    faultForm.annexs = data.annexs
    faultForm.id = data.id
    faultForm.name = data.name
    faultForm.content = data.content
    faultForm.solution = data.solution
    faultForm.status = data.status
    data.annexs.forEach((item) => {
      faultImg.value.push({
        uid: item.id,
        imgUrl: item.path,
      })
    })
    faultForm.knowledgeTypeVos = data.knowledgeTypeVos
    faultForm.solutions = data.solutions
    data.solutions.forEach((item) => {
      solveImg.value.push({
        uid: item.id,
        imgUrl: item.path,
      })
    })
    faultLoading.value = false
  }

  // 添加的数据
  const saveFaultData = (method, load, dialog, data) => {
    method(data).then((res) => {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
        dialog.value = false
        load.value = false
        getFaultList()
      } else {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: 'warning',
            duration: 2000,
          })
        load.value = false
        return
      }
    })
  }

  // 保存添加
  const saveAddFault = (formEl: FormInstance | undefined) => {
    formEl.validate(async (valid) => {
      if (valid) {
        faultLoading.value = true
        if (faultImg.value) {
          const files = []
          faultImg.value.forEach((item) => {
            if (item.file) {
              files.push(item.file.raw)
            }
          })
          if (files.length != 0) {
            await knowledgeAnnexUpload(files).then((res) => {
              res.data.data.rows.forEach((item, i) => {
                if (faultForm.annexs[i]?.path != item) {
                  faultForm.annexs.push({ path: item })
                }
              })
            })
          }
        }
        if (solveImg.value) {
          const files = []
          solveImg.value.forEach((item) => {
            if (item.file) {
              files.push(item.file.raw)
            }
          })
          if (files.length != 0) {
            await knowledgeAnnexUpload(files).then((res) => {
              res.data.data.rows.forEach((item, i) => {
                if (faultForm.solutions[i]?.path != item) {
                  faultForm.solutions.push({ path: item })
                }
              })
            })
          }
        }
        if (faultForm.delAnnexIds.length != 0) {
          await deleteFile(faultForm.delAnnexIds).then()
        }
        if (faultForm.delSolutionIds.length != 0) {
          await deleteFile(faultForm.delSolutionIds).then()
        }
        faultForm.knowledgeTypeVos = knowledgeMultipleRef.value.getKnowledgeSelectVal().value
        faultForm.delRelationIds = knowledgeMultipleRef.value.getDeleteKnowledgeSelectVal().value
        saveFaultData(saveFault, faultLoading, addFault_dialogVisible, faultForm)
      }
    })
  }

  // 清空搜索
  const clearVlaue = () => {
    name.value = ''
    content.value = ''
    solution.value = ''
  }

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val: any[]) => {
    if (val.length != 0) {
      val.forEach((item) => {
        if (selecttion.value.indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 修改状态的方法
  const changeMethod = (type, name, method, arr, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的${name}`,
        type: 'warning',
        duration: 2000,
      })
      return
    }
    ElMessageBox({
      type: type == '删除' ? 'error' : 'warning',
      title: '提示',
      icon: type == '删除' ? markRaw(Delete) : markRaw(Warning),
      message: `确认${type}选中的${name}?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = 'Loading...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 300)
          }, 1200)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (type == '删除') {
        await method(arr).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 2000,
          })
          if (dialog) {
            dialog.value = false
          }
        })
      } else {
        await method(arr, status).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 2000,
          })
        })
      }
      selecttion.value = []
      faulTableDom.value.clearSelection()
      getFaultList()
    })
  }

  // 批量启用/禁用/删除
  const changeAll = (n: number) => {
    if (n == 1) {
      changeMethod('启用', '故障', disableFault, selecttion.value, false, '')
    }
    if (n == 2) {
      changeMethod('禁用', '故障', disableFault, selecttion.value, true, '')
    }
    if (n == 3) {
      changeMethod('删除', '故障', deleteFault, selecttion.value, '', '')
    }
    if (n == 4) {
      changeMethod('删除', '故障', deleteFault, [faultForm.id], '', addFault_dialogVisible)
    }
  }

  onBeforeUnmount(() => {
    resizeObserver.disconnect()
  })

  onMounted(() => {
    resizeObserver.observe(dom.value) // 监听dom的变化
  })

  defineExpose({ getAllData })
</script>

<style scoped lang="scss">
  @import './index.scss';
</style>
